<script setup lang="ts">
import { ref,onMounted,onUnmounted } from 'vue';
import {
  get,
  post,
  postUploadFiles,
  postUploadFile,
  baseURL,
} from "./utils/api";
import type {
  IAgoraRTCClient,
  IAgoraRTCRemoteUser,
  ICameraVideoTrack,
  IMicrophoneAudioTrack,
  IRemoteAudioTrack,
} from "agora-rtc-sdk-ng";

import AgoraRTC from "agora-rtc-sdk-ng";
import { EMessageEngineMode, MessageEngine } from "./utils/message";

const messageListRef = ref<HTMLElement|null>(null);
// 消息列表
const messages = ref<string[]>([]);
// 输入框内容
const inputMessage = ref<string>('');

const agentId = ref<string>('');
const agoraAppId = "3669d0289d81403ab8c60566607fe6b8"
const agoraToken = "007eJxTYOi4+yzzVW7c6wmLX8rYrpLot5/G2hczyzz18878F+c7rE8oMBibmVmmGBhZWKZYGJoYGCcmWSSbGZiamZkZmKelmiVZHOk+n94QyMjAdFCMlZEBAkF8ZgZDQ0MGBgCiVR9j"

let isJoined = ref(false);
let isAudioOn = ref(false);
let isAudioPubed = ref(false);
let isAudioSubed = ref(false);
const channel = ref("111")
let client: IAgoraRTCClient;
let audioTrack: IMicrophoneAudioTrack;

let messageEngine: MessageEngine | null = null;

async function joinChannel() {
  if (!channel.value) {
    channel.value = "vue-room";
  }

  if (isJoined.value) {
    await leaveChannel();
  }

  if (!client) {
    client = AgoraRTC.createClient({
      mode: "rtc",
      codec: "vp8",
    });
    console.log("client", client);
    client.on("user-published", onUserPublish);
  }

  messageEngine = new MessageEngine(client,EMessageEngineMode.AUTO,(chatHistory)=>{
    // console.log("chatHistory",chatHistory);
    // console.log(typeof chatHistory)
    if (messages.value.length < chatHistory.length) {
      for (let i=messages.value.length;i<chatHistory.length;i++){
        console.log(chatHistory[i].text)
        messages.value.push(chatHistory[i].text)
      }

      nextTick(() => {
      if (messageListRef.value) {
        console.log("scrollTop",messageListRef.value.scrollHeight)
        messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
      } else {
        console.log("messageListRef is null");
      }
    });
    }

    window.postMessage({
      type:"chatHistory",
      chatHistory
    });
  });


  await client.join(agoraAppId, channel.value, agoraToken, null);
  isJoined.value = true;
}

async function leaveChannel() {
  isJoined.value = false;
  isAudioPubed.value = false;
  // isVideoPubed.value = false;

  client && (await client.leave());
}

async function onUserPublish(
  user: IAgoraRTCRemoteUser,
  mediaType: "video" | "audio"
) {
  // if (mediaType === "video") {
  //   const remoteTrack = await client.subscribe(user, mediaType);
  //   remoteTrack.play("remote-video");
  //   isVideoSubed.value = true;
  // }
  if (mediaType === "audio") {
    const remoteTrack = await client.subscribe(user, mediaType);
    remoteTrack.play();
    isAudioSubed.value = true;
  }
}


async function turnOnMicrophone() {
  isAudioOn.value = !isAudioOn.value;

  if (audioTrack) {
    return audioTrack.setEnabled(!audioTrack.enabled);
  }

  audioTrack = await AgoraRTC.createMicrophoneAudioTrack();
  // audioTrack.play();
}

async function publishAudio() {
  if (!isAudioOn.value) {
    await turnOnMicrophone();
  }
  if (!isJoined.value) {
    await joinChannel();
  }

  await client.publish(audioTrack);
  isAudioPubed.value = true;
}

// 发送消息
const sendMessage = async() => {
  if (inputMessage.value.trim()) {
    messages.value.push(inputMessage.value);
    const response = await post<{ list: object }>(
      "/send_message_to_agora",
      { message:inputMessage.value,agentId:agentId.value }
    );
    const result = JSON.parse(response.content);
    console.log(result.content);
    inputMessage.value = '';
    messages.value.push(result.content);

    nextTick(() => {
      if (messageListRef.value) {
        console.log("scrollTop",messageListRef.value.scrollHeight)
        messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
      } else {
        console.log("messageListRef is null");
      }
    });
  }
};

// 上传文件
const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    messages.value.push(`[文件] ${file.name}`);
    target.value = ''; // 重置文件输入
  }
};


onMounted(async () => {
  await joinChannel();
  await publishAudio();

  const response = await post<{ list: object }>(
      "/register",
      { name:"111" }
    );
    const result = JSON.parse(response.content);
    console.log(result.agent_id);
    agentId.value = result.agent_id;
});


onUnmounted(async () => {
  const response2 = await post<{ list: object }>(
      "/leave",
      { agentId: agentId.value}
    );
  console.log(response2);

  leaveChannel();

  messageEngine.clearup()
});
</script>

<template>
  <div class="chat-container">
    <div ref="messageListRef" class="message-list">
      <div v-for="(message, index) in messages" :key="index" class="message">
        {{ message }}
      </div>
    </div>
    <div class="input-area">
      <input type="file" @change="handleFileUpload" class="file-upload" />
      <input v-model="inputMessage" type="text" placeholder="输入消息..." class="message-input" />
      <button @click="sendMessage" class="send-button">发送</button>
    </div>
  </div>
</template>

<style scoped>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 90vh; /* 使容器占满整个视口高度 */
  width: 100%;
  border: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box; /* 确保内边距和边框不会增加高度 */
}

.message-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  margin: 5px 0;
  padding: 10px;
  background-color: #f1f1f1;
  border-radius: 5px;
}

.input-area {
  display: flex;
}

.file-upload {
  margin-right: 10px;
}

.message-input {
  flex: 1;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.send-button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0056b3;
}
</style>